package front2;

import java.util.ArrayList;

public class Th extends Commands implements frontRunnable {
	private int id;

	public Th(int thread) {
		this.id = thread;
	}
	public int run() {
		while(true){
			print();
			if(readCommand())
				continue;
			
			if(isDown()){
				//Cannot.
			}
			if(userID >= 0){
				if(isAdd()){
					String postContent = readCommand("The new post shall contain?");
					addPost(postContent);
				}
					
				if(isMod()){
					int postid = Integer.parseInt(readCommand("What's the id of the post?"));
					String newContent = readCommand("The posts text shall be changed to?");
					editPost(postid, newContent);
				}
			}else{
				System.out.println("This feature is not available for guests! please register and login!");
			}
			if(isLogout())
				return -1;
			if(isUp())
				return 0;
		}
	}

	public void print() {
		ArrayList<front.Post> posts = m.getAllPosts(id);

		for(front.Post s : posts)
			System.out.println(s.getPostID()+" "+s.getUserNameOfCreator() + ": " + s.getContent());
	}
	
	public void addPost(String postContent){
		
		if( postContent.equals("") || postContent.isEmpty()){
			System.out.println("Add Error! Usage: add <nameOfThread> <PostContent>");
		}
		else{
			front.Post p = new front.Post(id,userID,postContent);
			p.Create();
			m.getUser(userID).incrementNumberOfPosts();
		}
	}
	
	public void editPost(int postId,String newContent){
		
		if( userID == m.getPost(postId).getUserID())
			m.editPostContent(postId, newContent);
		else{
			System.out.println("You can only edit posts you created!");
		}
	}
}
